<?php

ini_set('display_errors', 'on');
error_reporting(E_ERROR);

//define('TAOBAOKE_ID', 'mm_10176789_0_0');
define('TAOBAOKE_ID', '10176789');

$url = 'http://gw.api.taobao.com/router/rest?';  //正式环境提交URL
$appKey = '21014814'; //填写自己申请的AppKey
$appSecret = 'f4d441766dd87878f6e6c520a95b2c6e'; //填写自己申请的$appSecret

//$url = 'http://gw.api.tbsandbox.com/router/rest?';
//$appKey = '1021014814'; //填写自己申请的AppKey
//$appSecret = 'sandbox66dd87878f6e6c520a95b2c6e'; //填写自己申请的$appSecret

//$userNick = 'leezjs'; //淘宝昵称
//
//获取数据兼容file_get_contents与curl

function vita_get_url_content($url) {
    if (!function_exists('file_get_contents')) {
        $file_contents = file_get_contents($url);
    } else {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }
    return $file_contents;
}

//签名函数
function createSign($paramArr) {
    global $appSecret;
    $sign = $appSecret;
    ksort($paramArr);
    foreach ($paramArr as $key => $val) {
        if ($key != '' && $val != '') {
            $sign .= $key . $val;
        }
    }
    $sign = strtoupper(md5($sign . $appSecret));
    return $sign;
}

//组参函数
function createStrParam($paramArr) {
    $strParam = '';
    foreach ($paramArr as $key => $val) {
        if ($key != '' && $val != '') {
            $strParam .= $key . '=' . urlencode($val) . '&';
        }
    }
    return $strParam;
}

//解析xml函数
function getXmlData($strXml) {
    $pos = strpos($strXml, 'xml');
    if ($pos) {
        $xmlCode = simplexml_load_string($strXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $arrayCode = get_object_vars_final($xmlCode);
        return $arrayCode;
    } else {
        return '';
    }
}

function get_object_vars_final($obj) {
    if (is_object($obj)) {
        $obj = get_object_vars($obj);
    }
    if (is_array($obj)) {
        foreach ($obj as $key => $value) {
            $obj[$key] = get_object_vars_final($value);
        }
    }
    return $obj;
}

// get shop information from taobao
function sendTaobaoRequest($sid) {
    global $appKey, $appSecret, $url;
    $paramArr = array(
        /* API系统级输入参数 Start */

        'method' => 'taobao.taobaoke.shops.convert', //API名称
        'timestamp' => date('Y-m-d H:i:s'),
        'format' => 'xml', //返回格式,本demo仅支持xml
        'app_key' => $appKey, //Appkey
        'v' => '2.0', //API版本号
        'sign_method' => 'md5', //签名方式

        /* API系统级参数 End */

        /* API应用级输入参数 Start */

        'fields' => 'user_id,click_url,pic_url,iid,shop_title,price,commission_rate,shop_type', //返回字段
        'sids' => $sid, //Num_iid
        'pid' => 10176789, //推广者昵称

            /* API应用级输入参数 End */
    );

//生成签名
    $sign = createSign($paramArr, $appSecret);

//组织参数
    $strParam = createStrParam($paramArr);
    $strParam .= 'sign=' . $sign;

//构造Url
    $urls = $url . $strParam;

//连接超时自动重试
    $cnt = 0;
    while ($cnt < 3 && ($result = @vita_get_url_content($urls)) === FALSE)
        $cnt++;

//解析Xml数据
    $result = getXmlData($result);

//获取错误信息
    return $result;
}

// main logic

require_once ( 'config.inc.php' );

$DBInstance = new DB();

$totalShopCount = $DBInstance->GetValue("select count(*) from shop_info_taobao where click_url=''");
$offset = 0;
$perStep = 100;

$logger = GetAuditLogger("shopinfo_audit.log");

while ($offset < $totalShopCount) {
    //每次更新不要太多，防止超过每分钟调用频率
    $ShopArr = $DBInstance->GetPlan("select s.id, s.shop_url,st.shop_id,st.taobao_id
        from shop_info_taobao st,shop_info s where st.shop_id=s.id and s.id>0 AND click_url=''
        limit $offset,$perStep");

    foreach ($ShopArr as $shop) {
        $extShopID = $shop['taobao_id']; //taobao店铺的id

        $TaobaokeDataInfo = sendTaobaoRequest($extShopID);
        if ( !edp_is_empty_string($TaobaokeDataInfo['taobaoke_shops']['taobaoke_shop']['click_url']) ) {
            $commissionURL = $TaobaokeDataInfo['taobaoke_shops']['taobaoke_shop']['click_url'];
            $commissionRate = $TaobaokeDataInfo['taobaoke_shops']['taobaoke_shop']['commission_rate'];
            $shop_title = $TaobaokeDataInfo['taobaoke_shops']['taobaoke_shop']['shop_title'];
            
            try {
                $DBInstance->BeginTransaction();

                $sql = "update shop_info_taobao set click_url='" . $commissionURL . "',commission_rate='" . $commissionRate . "', update_time=NOW() where shop_id =" . $shop['id'];
                $DBInstance->Update($sql);

                $sql = "select shop_name from shop_info where id=" . $shop['id'];
                if ($shop_title != $DBInstance->GetValue($sql)) {
                    $shop_title = mysql_real_escape_string( stripslashes( $shop_title ) );
                    $sql = "update shop_info set shop_name='" . $shop_title . "' where id =" . $shop['id'];
                    $DBInstance->Update($sql);
                }

                $logger->error($shop['id'] . " successfully process");
            } catch (Exception $e) {
                $DBInstance->Rollback();
                return false;
            }

            $DBInstance->Commit();

            sleep(1);
        }
	else {
	    $shop_click_url = "http://shop".$shop['id'].".taobao.com";
	    $sql = "update shop_info_taobao set click_url='',commission_rate='0', update_time=NOW() where shop_id =" . $shop['id'];
	    $DBInstance->Update($sql);
	    $logger->error($shop['id'] . " use default shop urls");
	}
    }

    $offset = $offset + $perStep;
    echo "processing.....$offset.....\n";

}

$DBInstance->Disconnect();

echo "finished!";
?>
